const DEFAULT_COUNTDOWN = 3 // 默认的倒计时时间

/**
 * 倒计时类
 * @param {string} target 需要渲染的目标元素id
 * @param {number} number 自定义倒计时时间
 * @method startCountdown 开始倒计时
 * @method stopCountdown  停止倒计时
 */
class CountDown {

    constructor(target, number) {
        if (typeof target !== 'string') {
            throw TypeError(`target element id should be a string, but got ${typeof target}`)
        }
        this.targetId = target
        if (typeof number === 'number' && number > 0) {
            this.countdown = number
        }
    }

    targetId = undefined // 要渲染的目标元素id
    targetDom = null // 要渲染的目标元素DOM
    useRAF = (typeof window.requestAnimationFrame === 'function') && (typeof window.cancelAnimationFrame === 'function')
    countdown = DEFAULT_COUNTDOWN
    timer = undefined
    lastTimestamp = undefined // raf记录的上一帧时间戳

    render = () => {
        if (this.targetDom === null) {
            const el = document.getElementById(this.targetId)
            if (el) {
                this.targetDom = el
            } else {
                return
            }
        }
        this.targetDom.textContent = this.countdown
    }
    
    setTimeoutCallback = () => {
        this.countdown -= 1
        this.render()
        if (this.countdown < 1) {
            window.clearTimeout(this.timer)
            return
        }
        this.timer = window.setTimeout(this.setTimeoutCallback, 1000)
    }

    rafCallback = (timestamp = 0) => {
        if (this.lastTimestamp === undefined) {
            this.lastTimestamp = timestamp
        }
        if (timestamp - this.lastTimestamp >= 1000) {
            this.lastTimestamp = timestamp
            this.countdown -= 1
            this.render()
        }
        if (this.countdown < 1) {
            window.cancelAnimationFrame(this.timer)
            return
        }
        this.timer = window.requestAnimationFrame(this.rafCallback)
    }


    startCountdown = () => {
        this.render()
        if (this.useRAF) {
            this.rafCallback()
        } else {
            this.setTimeoutCallback()
        }
    }

    stopCountdown = () => {
        if (this.useRAF) {
            window.cancelAnimationFrame(this.timer)
        } else {
            window.clearTimeout(this.timer)
        }
    }

}

// cjs
module.exports = CountDown

// esm
export default CountDown

// browser
if (window) {
    window.CountDown = CountDown
}
